//
//  CBCChannelViewController.m
//  CBCChannelControl
//
//  Created by 李雷川 on 2019/6/30.
//  Copyright © 2019 李雷川. All rights reserved.
//

#import "CBCChannelViewController.h"
#import "CBCChannelCell.h"
#import "CBCChannelReusableView.h"
#import "CBCChannelAddCell.h"
#import "CBCChannelManager.h"
#import "CBCChannelModel.h"
#import "CBCConnerView.h"
@interface CBCChannelViewController ()<UICollectionViewDelegate,UICollectionViewDataSource>
@property(nonatomic, assign)BOOL isEditing;
@property(nonatomic, retain)UICollectionView *collectionView;
@property(nonatomic, retain)CBCConnerView *containerView;
    
    
@end

@implementation CBCChannelViewController

static NSString * const cellReuseIdentifier = @"cellReuseIdentifier";
static NSString * const addCellReuseIdentifier = @"addCellReuseIdentifier";
static NSString * const reusableViewReuseIdentifier = @"reusableViewReuseIdentifier";

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor =  [UIColor colorWithRed:0 green:0 blue:0 alpha:0.4];
    [self.view addSubview:self.containerView];
    [self.containerView addSubview:self.collectionView];
    [self setupGesture];

}
-(void)dealloc{
    NSLog(@"dealloc");
}

-(void)setSelectIndex:(NSUInteger)selectIndex{
    _selectIndex = selectIndex;
    [self.collectionView reloadData];
}
-(void)setupGesture {
    UILongPressGestureRecognizer *longPressGesture = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(handleLongPress:)];
    [self.collectionView addGestureRecognizer:longPressGesture];
}


-(void)handleLongPress:(UILongPressGestureRecognizer *)gesture{
    CGPoint point  = [gesture locationInView:self.collectionView];
    switch (gesture.state) {
        case UIGestureRecognizerStateBegan:{
            NSIndexPath *indexPath = [self.collectionView indexPathForItemAtPoint:point];
            [self.collectionView beginInteractiveMovementForItemAtIndexPath:indexPath];
        }
            break;
        case UIGestureRecognizerStateChanged:{
            [self.collectionView updateInteractiveMovementTargetPosition:point];
        }
            break;
        case UIGestureRecognizerStateEnded:
            [self.collectionView endInteractiveMovement];
            break;
        default:
            [self.collectionView cancelInteractiveMovement];
            break;
    }
}

-(void)close{
    [self removeFromParentViewController];
    [self.view removeFromSuperview];
}

-(CBCConnerView *)containerView{
    if(_containerView == nil){
        NSUInteger topMargin = 92;
        _containerView = [CBCConnerView new];
        _containerView.frame =  CGRectMake(0, topMargin, CGRectGetWidth(self.view.frame), CGRectGetHeight(self.view.frame) -topMargin);
    }
    return _containerView;
}

-(UICollectionView *)collectionView{
    if(_collectionView == nil){
   
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
        layout.itemSize = CGSizeMake(64, 24);
        layout.minimumLineSpacing = 16;
        layout.minimumInteritemSpacing = 18;
        layout.headerReferenceSize = CGSizeMake(self.view.frame.size.width, 88);
        layout.sectionInset = UIEdgeInsetsMake(18, 40, 18, 40);
        _collectionView.collectionViewLayout = layout;
        _collectionView = [[UICollectionView alloc]initWithFrame:self.containerView.bounds collectionViewLayout:layout];
        _collectionView.backgroundColor = [UIColor whiteColor];
        [_collectionView registerClass:[CBCChannelCell class] forCellWithReuseIdentifier:cellReuseIdentifier];
        [_collectionView registerClass:[CBCChannelAddCell class] forCellWithReuseIdentifier:addCellReuseIdentifier];
        [_collectionView registerClass:[CBCChannelReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:reusableViewReuseIdentifier];
        _collectionView.delegate = self;
        _collectionView.dataSource= self;

    }
    return _collectionView;
}
#pragma mark <UICollectionViewDataSource>

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if(section == 0){
        return [CBCChannelManager shared].inUseItems.count;
    }else{
        return [CBCChannelManager shared].unUseItems.count;
    }
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    CBCChannelReusableView *reusableView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:reusableViewReuseIdentifier forIndexPath:indexPath];
    if(indexPath.section == 0){
        reusableView.titleLabel.text = @"频道列表";
        reusableView.infoLabel.text = @"点击跳转频道";

        __weak typeof(self) weakSelf = self;
        reusableView.exitBlcok = ^{
            [weakSelf close];
        };
        reusableView.editBlock = ^(CBCChannelReusableView *view) {
            weakSelf.isEditing = !weakSelf.isEditing;
            if(weakSelf.isEditing){
                [view.editButton setTitle:@"完成" forState:UIControlStateNormal];
            }else{
                [view.editButton setTitle:@"编辑" forState:UIControlStateNormal];
            }
            NSMutableArray *indexPaths = [NSMutableArray arrayWithCapacity:[CBCChannelManager shared].inUseItems.count];
            for (NSInteger i = 0;i<[CBCChannelManager shared].inUseItems.count;i++){
                NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
                [indexPaths addObject:indexPath];
            }
            [self.collectionView reloadItemsAtIndexPaths:indexPaths];
        };

    }else{
        reusableView.titleLabel.text = @"添加频道";
        reusableView.infoLabel.text = @"点击添加频道";
        reusableView.closeButton.hidden = YES;
        reusableView.editButton.hidden = YES;
    }
    return reusableView;
    
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {

    if(indexPath.section == 0){
        CBCChannelCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellReuseIdentifier forIndexPath:indexPath];
        CBCChannelModel *channelModel = [CBCChannelManager shared].inUseItems[indexPath.row];
        cell.titleLabel.text = channelModel.title;
        cell.imageView.hidden = !self.isEditing;
        return cell;
    }else{
        CBCChannelAddCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:addCellReuseIdentifier forIndexPath:indexPath];
        CBCChannelModel *channelModel = [CBCChannelManager shared].unUseItems[indexPath.row];
        cell.titleLabel.text = channelModel.title;
        return cell;
    }
}


-(void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath{
    cell.selected = indexPath.row == _selectIndex ? YES:NO;
}
#pragma mark <UICollectionViewDelegate>
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.section == 1){
        [self.collectionView performBatchUpdates:^{
            CBCChannelModel *channelModel = [CBCChannelManager shared].unUseItems[indexPath.row];
            NSIndexPath *toIndexPath = [NSIndexPath indexPathForRow:[CBCChannelManager shared].inUseItems.count inSection:0];
            [[CBCChannelManager shared].inUseItems addObject:channelModel];
            [[CBCChannelManager shared].unUseItems removeObjectAtIndex:indexPath.row];
            
            CBCChannelAddCell *cell = (CBCChannelAddCell *)[self.collectionView cellForItemAtIndexPath:indexPath];
            cell.backgroundColor = [UIColor redColor];
            
            [self.collectionView moveItemAtIndexPath:indexPath toIndexPath:toIndexPath];
            
        } completion:^(BOOL finished) {
        }];
    }else{
        if(self.isEditing){
            [self.collectionView performBatchUpdates:^{
                CBCChannelModel *channelModel = [CBCChannelManager shared].inUseItems[indexPath.row];
                NSIndexPath *toIndexPath = [NSIndexPath indexPathForRow:0 inSection:1];
                [[CBCChannelManager shared].unUseItems addObject:channelModel];
                [[CBCChannelManager shared].inUseItems removeObjectAtIndex:indexPath.row];
                [self.collectionView moveItemAtIndexPath:indexPath toIndexPath:toIndexPath];
            } completion:^(BOOL finished) {
            }];
        }else{
            self.itemSelect(indexPath.row);
            [self close];
            
        }
    }
    
  
}

- (BOOL)collectionView:(UICollectionView *)collectionView canMoveItemAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.section == 1){
        return NO;
    }
    return YES;
}

- (void)collectionView:(UICollectionView *)collectionView moveItemAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath{
    CBCChannelModel *channelModel = [CBCChannelManager shared].inUseItems[sourceIndexPath.row];
    
    [[CBCChannelManager shared].inUseItems removeObjectAtIndex:sourceIndexPath.row];
    [[CBCChannelManager shared].inUseItems insertObject:channelModel atIndex:destinationIndexPath.row];
}


@end
